package cn.wolfcode.rbac.springsecurity.service.impl;

import cn.wolfcode.rbac.springsecurity.detail.EmployeeDetails;
import cn.wolfcode.rbac.springsecurity.service.AuthenticationService;
import cn.wolfcode.rbac.utils.SecurityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service("employeeAuthentication")
public class AuthenticationServiceImpl implements AuthenticationService {


    @Override
    public Boolean hasAuthority(String expression) {
        //通过上下文中获取用户信息
        EmployeeDetails employeeDetails = SecurityUtils.getUserDetails();
        //如果是超级管理员，则返回true
        if (employeeDetails.getEmployee().getAdmin()) {
            return true;
        }

        //如果不是超级管理员，则判断是否有该权限
        Collection<? extends GrantedAuthority> authorities = employeeDetails.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if(authority.toString().equals(expression)){
                return true;
            }
        }

        return false;
    }
}
